﻿using SQLite;

namespace LibraryProject.Tool;

public class SqLiteConnectionPro {
    // 数据库文件名
    public const string DbName = "linkFileProject.sqlite";

    // 数据库文件路径
    public static readonly string DbPath =
        Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder
                .LocalApplicationData), DbName);

    // 数据库链接
    private static SQLiteAsyncConnection? _connection;

    // 初始化数据库链接
    public static SQLiteAsyncConnection Connection =>
        _connection ??= new SQLiteAsyncConnection(DbPath);

    public static async Task<int> CreateTable<T>(string tableName) where T : new() {
        // 检查表是否存在
        var tableInfo = await Connection.GetTableInfoAsync(tableName);
        if (tableInfo == null || tableInfo.Count == 0) { // 表不存在时，tableInfo长度为0
            try {
                await Connection.CreateTableAsync<T>(); // 创建表
                return 1;
            } catch (Exception) { // 创建表失败
                return -1;
            }
        }

        return 0; // 表已存在，无需创建
    }
}